package com.pkk.alert.web.config.dynamic;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
 * 动态修改任务配置
 *
 * @author peikunkun<br>
 * @version V1.0<br>
 * @date 2020/11/3 0003 下午 4:03<br>
 * @since <><br>
 */
@Slf4j
@Configuration
public class DynamicScheduleConfiguration implements ApplicationContextAware {


  private ApplicationContext applicationContext;
 /*

  private void onChange(ConfigChangeEvent changeEvent) {
    refreshProperties(changeEvent.changedKeys());

    //处理
    this.handle(changeEvent);

  }

  */

  /**
   * 处理配置
   *
   * @return void
   * @Param changeEvent
   * @author peikunkun
   * @date 2020/11/3 0003 下午 5:06
   * @since
   *//*
  private void handle(ConfigChangeEvent changeEvent) {
    changeEvent.changedKeys().stream().forEach(c -> {
      if (StringUtil.isBlank(c) || !c.startsWith("com.pkk.schedule.info")) {
        return;
      }

      String taskId = ScheduleContent.getScheduleId(c);
      final ConfigChange change = changeEvent.getChange(c);
      switch (change.getChangeType()) {
        case DELETED:
          SUCCESS_SCHEDULE.remove(taskId);
          CANCEL_SCHEDULE.add(taskId);
          log.warn("【定时任务】-[配置修改]-删除定时任务-[{}],配置信息:[{}]", c, JSONObject.toJSONString(change));
          break;
        case ADDED:
          final ScheduleInfo scheduleInfo = ScheduleInfo.buildScheduleInfo(taskId, change.getNewValue());
          if (!ScheduleInfo.verifySchedule(scheduleInfo)) {
            log.error("【定时任务】-[错误配置]-新增定时任务-[{}],错误配置:[{}]", c, JSONObject.toJSONString(change));
            break;
          }
          SUCCESS_SCHEDULE.put(taskId, scheduleInfo);
          log.warn("【定时任务】-[配置修改]-新增定时任务-[{}],配置信息:[{}]", c, JSONObject.toJSONString(change));
          break;
        case MODIFIED:
          final ScheduleInfo scheduleInfo1 = ScheduleInfo.buildScheduleInfo(taskId, change.getNewValue());
          if (!ScheduleInfo.verifySchedule(scheduleInfo1)) {
            log.error("【定时任务】-[错误配置]-修改定时任务-[{}],错误配置:[{}]", c, JSONObject.toJSONString(change));
            break;
          }
          SUCCESS_SCHEDULE.put(taskId, scheduleInfo1);
          log.warn("【定时任务】-[配置修改]-修改定时任务-[{}],配置信息:[{}]", c, JSONObject.toJSONString(change));
          break;
        default:
          log.error("【定时任务】-[配置修改]-无法找到相对应的定时任务,请确认:[{}]", JSONObject.toJSONString(change));
          break;
      }
    });
  }

  private void refreshProperties(Set<String> changedKeys) {
    this.applicationContext.publishEvent(new EnvironmentChangeEvent(changedKeys));
  }*/
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
  }
}
